package com.byx.imclientutil.netty;

import com.byx.imclientutil.protobuf.ChatMessageProtobuf;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * NettyWebSocketChannelInitializer
 *
 * @author Superb
 * @date 2021/2/9 18:23
 */
public class NettyWebSocketChannelInitializer extends ChannelInitializer<Channel> {
    private NettyWebSocketClientImpl imService;

    public NettyWebSocketChannelInitializer(NettyWebSocketClientImpl imService) {
        this.imService = imService;
    }

    /**
     * This method will be called once the {@link Channel} was registered. After the method returns this instance
     * will be removed from the {@link ChannelPipeline} of the {@link Channel}.
     *
     * @param ch the {@link Channel} which was registered.
     * @throws Exception is thrown if an error occurs. In that case it will be handled by
     *                   {@link #exceptionCaught(ChannelHandlerContext, Throwable)} which will by default close
     *                   the {@link Channel}.
     */
    @Override
    protected void initChannel(Channel ch) throws Exception {
        ChannelPipeline pipeline=ch.pipeline();
        pipeline.addLast(new ProtobufDecoder(ChatMessageProtobuf.Msg.getDefaultInstance()));
        pipeline.addLast(new ProtobufEncoder());
        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast(LoginAuthHandler.class.getSimpleName(),new LoginAuthHandler(imService));
        pipeline.addLast(HeartBeatRespHandler.class.getSimpleName(),new HeartBeatRespHandler(imService));
        pipeline.addLast(NettyWebSocketHandler.class.getSimpleName(),new NettyWebSocketHandler(imService));
    }
}
